<?php

namespace App\Http\Controllers\Api;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Overtrue\EasySms\EasySms;

use App\Http\Requests\Api\VerificationCodeRequest;

class VerificationCodesController extends Controller{
    public function store(VerificationCodeRequest $request,EasySms $easySms){
        $captchaData = \Cache::get($request->captcha_key);
        if(!$captchaData){
            return $this->response->error('图片验证码已失效',422);
        }
        if(!hash_equals($request->captcha_code,$captchaData['code'])){
            // 验证码错误就清除缓存
            \Cache::forget($request->captcha_key);
            return $this->response->errorUnauthorized('验证码错误');
        }

        $phone = $captchaData['phone'];

        if(app()->isLocal()){
            $code = '1234';
        }else{
            // 生成 4 位随机数
            $code = str_pad(mt_rand(1,9999),4,0,STR_PAD_LEFT);
            try{
                $result = $easySms->send($phone,[
                    'content' => '【Lbbs社区】您的验证码是{$code}。如非本人操作，请忽略本短信'
                ]);
            }catch(\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $e){
                /*
                $message = $e->getException('chuanglan')->getMessage();
                return $this->response->errorInternal($message ?? '短信发送异常');
                */
                $response = $e->getResponse();
                $result = json_decode($response->getBody()->getContents(),true);
                return $this->response->errorInternal($result['msg'] ?? '短信发送异常');
            }
        }

        $key = 'verificationCode_'.str_random(15);
        $expiredAt = Carbon::now()->addMinutes(10);
        \Cache::put($key,['phone'=>$phone,'code' =>$code],$expiredAt);
        // 清除图片验证码缓存
        \Cache::forget($request->captcha_key);
        return $this->response->array([
            'key' => $key,
            'expired_at' => $expiredAt->toDateTimeString(),
        ])->setStatusCode(201);
    }
}
